package com.cq.hd.order.factory.orderSelect;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.common.enums.ResponseEnums;
import com.cq.hd.common.enums.biz.*;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Throw;
import com.cq.hd.order.api.dto.ActiveEnrollInfoOptionDto;
import com.cq.hd.order.api.dto.ActiveEnrollInfoSonDto;
import com.cq.hd.order.api.dto.AppOrderDetailDto;
import com.cq.hd.order.api.dto.AppOrderPageDto;
import com.cq.hd.order.api.vo.*;
import com.cq.hd.order.mapper.TbOrderItemMapper;
import com.cq.hd.order.mapper.TbOrderMapper;
import com.cq.hd.order.po.TbOrderItemPo;
import com.cq.hd.order.po.TbOrderPo;
import com.cq.hd.order.service.TbGroupBuyOrderService;
import com.cq.hd.product.api.TbActiveApi;
import com.cq.hd.product.api.TbActiveStepPriceApi;
import com.cq.hd.product.api.dto.ActiveDto;
import com.cq.hd.product.api.vo.ActivePageVo;
import com.cq.hd.product.api.vo.ActiveSimpleVo;
import com.cq.hd.product.api.vo.ActiveStepPriceVo;
import com.cq.hd.product.api.vo.ActiveVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
@Slf4j
public class BuyOrderSelectHandler extends AbstractOrderSelectHandler {

    @Autowired
    private TbOrderMapper orderMapper;

    @Autowired
    private TbOrderItemMapper orderItemMapper;

    @Autowired
    private TbActiveStepPriceApi activeStepPriceApi;

    @Autowired
    private TbActiveApi activeApi;

    @Autowired
    private TbGroupBuyOrderService groupBuyOrderService;

    @Override
    protected Integer getType() {
        return OrderSelectTypeEnum.BUY.getValue();
    }

    @Override
    public Page<AppOrderPageVo> pageAppOrder(AppOrderPageDto appOrderPageDto) {
        Long userId = appOrderPageDto.getUserId();
        if (userId == null || userId <= 0) {
            Throw.isBusinessException(ResponseEnums.USER_ACCESS_DENIED);
        }

        PageHelper.startPage(appOrderPageDto.getPageNum(), appOrderPageDto.getPageSize());
        List<AppOrderPageVo> orderPageVoList = orderMapper.listAppBuyOrderByDto(appOrderPageDto);
        if (!CollectionUtils.isEmpty(orderPageVoList)) {
            List<Long> activeIds = orderPageVoList.stream().map(AppOrderPageVo::getActiveId).collect(Collectors.toList());

            Map<Long, List<TbOrderItemPo>> activeEnrollOrderItemPoMap = new HashMap<>();
            // 根据活动id查询活动报名订单项列表
            List<TbOrderItemPo> activeEnrollOrderItemPos = orderItemMapper.selectList(new QueryWrapper<TbOrderItemPo>().eq("del_state", 0)
                    .in("active_id", activeIds));
            if (!CollectionUtils.isEmpty(activeEnrollOrderItemPos)) {
                activeEnrollOrderItemPoMap = activeEnrollOrderItemPos.stream().collect(Collectors.groupingBy(TbOrderItemPo::getActiveId));
            }

            // 根据活动id查询阶梯价格列表
            Map<Long, List<ActiveStepPriceVo>> activeStepPriceVoMap = new HashMap<>();
            List<ActiveStepPriceVo> activeStepPriceVos = activeStepPriceApi.listByActiveIds(activeIds).unpack();
            if (!CollectionUtils.isEmpty(activeStepPriceVos)) {
                activeStepPriceVoMap = activeStepPriceVos.stream().collect(Collectors.groupingBy(ActiveStepPriceVo::getActiveId));
            }

            for (AppOrderPageVo appOrderPageVo : orderPageVoList) {
                Long activeId = appOrderPageVo.getActiveId();
                Integer orderType = appOrderPageVo.getOrderType();
                BigDecimal activePrice = appOrderPageVo.getActivePrice();
                // 是否是阶梯价格(1-否，2-是)
                Integer stepPriceState = appOrderPageVo.getStepPriceState();
                // 未满员是否自动退款:1-是，2-否
                Integer noFullAutoRefundState = appOrderPageVo.getNoFullAutoRefundState();
                Integer totalStock = appOrderPageVo.getTotalStock();
                LocalDateTime endTime = appOrderPageVo.getEndTime();

                if (!ActiveTypeEnum.ENROLL.getValue().equals(orderType)) {
                    continue;
                }

                int missNum = 0;
                String inviteReturnMsg = "";
                if (StepPriceStateEnum.NO.getValue().equals(stepPriceState)) {
                    // 固定报名人数，未满员订单，显示”差x人满员“；
                    // 固定人数、开启未满自动退的，列表显示还差x人
                    if (NoFullAutoRefundStateEnum.YES.getValue().equals(noFullAutoRefundState)) {
                        // 匹配对应活动的报名用户数据
                        List<TbOrderItemPo> activeEnrollOrderItemPoList = activeEnrollOrderItemPoMap.get(activeId);
                        if (CollectionUtils.isEmpty(activeEnrollOrderItemPoList)) {
                            continue;
                        }

                        // 当前报名活动已经报名成功的用户数
                        int enrolledNum = 0;
                        // 过滤符合报名条件的用户（只要在活动结束前没取消的都算，活动结束后取消也算）
                        for (TbOrderItemPo orderItemPo : activeEnrollOrderItemPoList) {
                            // 如果用户取消参与活动，且活动结束时间不早于取消活动时间，则不计入报名用户数
                            if (SubOrderStateEnum.CANCEL.getValue().equals(orderItemPo.getSubOrderState())
                                    && endTime.compareTo(orderItemPo.getCancelTime()) >= 0) {
                                continue;
                            }

                            enrolledNum += 1;
                        }
                        int remainNum = totalStock - enrolledNum;
                        if (remainNum > 0) {
                            missNum = remainNum;
                            inviteReturnMsg = String.format("差%s人满员", remainNum);
                        }
                    }
                } else {
                    // 阶梯人数，再邀x人，可返x元（报名订单，我购买的订单）

                    // 匹配对应活动的阶梯价格配置
                    List<ActiveStepPriceVo> activeStepPrices = activeStepPriceVoMap.get(activeId);
                    if (CollectionUtils.isEmpty(activeStepPrices)) {
                        continue;
                    }

                    // 根据阶梯报名人数正序
                    activeStepPrices = activeStepPrices.stream()
                            .sorted(Comparator.comparing(ActiveStepPriceVo::getEnrollNum))
                            .collect(Collectors.toList());

                    // 匹配对应活动的报名用户数据
                    List<TbOrderItemPo> activeEnrollOrderItemPoList = activeEnrollOrderItemPoMap.get(activeId);
                    if (CollectionUtils.isEmpty(activeEnrollOrderItemPoList)) {
                        continue;
                    }

                    // 当前报名活动已经报名成功的用户数
                    int enrolledNum = 0;
                    // 过滤符合报名条件的用户（只要在活动结束前没取消的都算，活动结束后取消也算）
                    for (TbOrderItemPo orderItemPo : activeEnrollOrderItemPoList) {
                        // 如果用户取消参与活动，且活动结束时间不早于取消活动时间，则不计入报名用户数
                        if (SubOrderStateEnum.CANCEL.getValue().equals(orderItemPo.getSubOrderState())
                                && endTime.compareTo(orderItemPo.getCancelTime()) >= 0) {
                            continue;
                        }

                        enrolledNum += 1;
                    }

                    ActiveStepPriceVo activeStepPriceVo = activeStepPrices.get(0);
                    Integer firstEnrollNum = activeStepPriceVo.getEnrollNum();
                    if (enrolledNum < firstEnrollNum) {
                        missNum = firstEnrollNum - enrolledNum;
                        // 报名成功，未满第一档人数，支付完成后提示：还差x人即可开启活动
                        inviteReturnMsg = String.format("还差%s人即可开启活动", missNum);
                    } else {
                        // 报名成功，满第一档人数，支付完成后提示：再邀x人，可返y元（对比第二档人数，逐级判断）

                        // 再邀x人
                        int inviteNum = 0;
                        // 可返x元
                        BigDecimal returnAmt = BigDecimal.ZERO;
                        for (ActiveStepPriceVo activeStepPrice : activeStepPrices) {
                            Integer enrollNum = activeStepPrice.getEnrollNum();
                            BigDecimal enrollPrice = activeStepPrice.getEnrollPrice();

                            // 取下一阶级的报名人数对比，如果都没匹配上，则表示已满员
                            if (enrolledNum < enrollNum) {
                                // 计算再邀人数=下一阶级报名人数-已报名人数
                                inviteNum = enrollNum - enrolledNum;
                                // 计算可返金额=当前报名价格-对应阶级报名价格
                                returnAmt = activePrice.subtract(enrollPrice);
                                break;
                            }
                        }

                        if (inviteNum != 0 && returnAmt.compareTo(BigDecimal.ZERO) > 0) {
                            appOrderPageVo.setInviteNum(inviteNum);
                            appOrderPageVo.setReturnAmt(returnAmt);
                            inviteReturnMsg = String.format("再邀%s人，可返%s元", inviteNum, returnAmt);
                        }
                    }
                }

                appOrderPageVo.setMissNum(missNum);
                appOrderPageVo.setInviteReturnMsg(inviteReturnMsg);
            }
        }
        PageInfo<AppOrderPageVo> pageInfo = new PageInfo<>(orderPageVoList);
        // 处理拼团信息
        processGroupBuyOrderInfo(orderPageVoList);

        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    // 拼团订单信息
    private void processGroupBuyOrderInfo(List<AppOrderPageVo> appOrderPageVos) {
        if (CollectionUtils.isEmpty(appOrderPageVos)) {
            return;
        }
        List<AppOrderPageVo> groupBuyOrderList = appOrderPageVos.stream()
                .filter(e -> PromotionTypeEnum.GROUP_BUY.name().equals(e.getPromotionType())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(groupBuyOrderList)) {
            return;
        }
        List<Long> orderIds = groupBuyOrderList.stream().map(AppOrderPageVo::getId).collect(Collectors.toList());
        List<GroupBuyOrderDetailVo> groupBuyOrderDetailVos = groupBuyOrderService.listDetailByOrderIds(orderIds);
        Map<Long, GroupBuyOrderDetailVo> orderIdToGroupDetailMap = groupBuyOrderDetailVos.stream()
                .collect(Collectors.toMap(GroupBuyOrderDetailVo::getOrderId, Function.identity()));
        for (AppOrderPageVo appOrderPageVo : appOrderPageVos) {
            GroupBuyOrderDetailVo groupBuyOrderDetailVo = orderIdToGroupDetailMap.get(appOrderPageVo.getId());
            appOrderPageVo.setGroupBuyOrderInfo(groupBuyOrderDetailVo);
        }

        // 拼团活动即便是单独购买，也要有一个标识，给前端判断报名详情按钮是否展示
        ActiveDto activeDto = new ActiveDto();
        List<Long> activeIds = appOrderPageVos.stream().map(AppOrderPageVo::getActiveId).collect(Collectors.toList());
        activeDto.setActiveIds(activeIds);
        List<ActivePageVo> activeList = activeApi.listByDto(activeDto).unpack();
        Map<Long, ActivePageVo> activeMap = activeList.stream().collect(Collectors.toMap(ActivePageVo::getId, Function.identity()));
        for (AppOrderPageVo appOrderPageVo : appOrderPageVos) {
            ActivePageVo activePageVo = activeMap.get(appOrderPageVo.getActiveId());
            if (activePageVo != null) {
                appOrderPageVo.setActivePromotionType(activePageVo.getPromotionType());
            }
        }

    }

    @Override
    public AppOrderDetailVo appOrderDetail(AppOrderDetailDto appOrderDetailDto) {
        log.info("appOrderDetailDto:{}", JSON.toJSON(appOrderDetailDto));
        String orderNo = appOrderDetailDto.getOrderNo();
        Long id = appOrderDetailDto.getId();
        if (id == null || id <= 0) {
            if (StringUtils.isEmpty(orderNo)) {
                Throw.isBusinessException("未找到订单数据");
            }
        }

        Long userId = appOrderDetailDto.getUserId();
        if (userId == null || userId <= 0) {
            Throw.isBusinessException(ResponseEnums.USER_ACCESS_DENIED);
        }

        AppOrderDetailVo appOrderDetailVo = orderMapper.getAppBuyOrderByDto(appOrderDetailDto);
        if (appOrderDetailVo == null) {
            Throw.isBusinessException("未找到订单数据");
        }

        Long activeId = appOrderDetailVo.getActiveId();
        // 是否是阶梯价格(1-否，2-是)
        Integer stepPriceState = appOrderDetailVo.getStepPriceState();
        // 未满员是否自动退款:1-是，2-否
        Integer noFullAutoRefundState = appOrderDetailVo.getNoFullAutoRefundState();
        Integer totalStock = appOrderDetailVo.getTotalStock();
        Integer orderType = appOrderDetailVo.getOrderType();
        BigDecimal orderPrice = appOrderDetailVo.getOrderPrice();
        LocalDateTime endTime = appOrderDetailVo.getEndTime();

        // 查找子订单列表
        List<AppOrderItemVo> appOrderItems = orderItemMapper.listByOrderId(appOrderDetailVo.getId());

        // 查找该活动下单成功人数(购买团购订单存在)
        if (ActiveTypeEnum.GROUP.getValue().equals(orderType)) {
            Integer orderUserNum = orderMapper.selectCount(new QueryWrapper<TbOrderPo>().eq("del_state", 0)
                    .eq("active_id", appOrderDetailVo.getActiveId())
                    .in("order_state", Arrays.asList(OrderStateEnum.WAIT_PAY.getValue(),
                            OrderStateEnum.WAIT_VERIFY.getValue(),
                            OrderStateEnum.VERIFYING.getValue(),
                            OrderStateEnum.VERIFIED.getValue(),
                            OrderStateEnum.FINISH.getValue())));
            appOrderDetailVo.setOrderUserNum(orderUserNum == null ? 0 : orderUserNum);
        } else if (ActiveTypeEnum.ENROLL.getValue().equals(orderType) || ActiveTypeEnum.GROUP_ENROLL.getValue().equals(orderType)) {
            ActiveSimpleVo activeSimpleVo = activeApi.getSimpleVoById(activeId).unpack();
            appOrderDetailVo.setActiveMobile(activeSimpleVo.getActiveMobile());
            appOrderDetailVo.setActiveWechat(activeSimpleVo.getActiveWechat());
            // 签到信息
            processSignInInfo(appOrderItems, appOrderDetailVo);
            // 返现信息
            processInviteReturnMsg(stepPriceState, activeId, endTime, orderPrice, appOrderDetailVo);
            // 报名信息（购买报名订单存在）
            processEnrollInfo(appOrderItems, appOrderDetailVo);

        }
        appOrderDetailVo.setAppOrderItems(appOrderItems);

        // 活动的营销类型
        ActiveVo activeVo = activeApi.getById(appOrderDetailVo.getActiveId()).unpack();
        appOrderDetailVo.setActivePromotionType(activeVo.getPromotionType());

        return appOrderDetailVo;
    }

    private void processSignInInfo(List<AppOrderItemVo> appOrderItems, AppOrderDetailVo appOrderDetailVo) {
        // 如果是纯报名活动，签到状态一定是打开
        if (ActiveTypeEnum.ENROLL.getValue().equals(appOrderDetailVo.getOrderType())) {
            appOrderDetailVo.setSignInRequired(1);
        }
        // 报名子单
        List<AppOrderItemVo> enrollOrderItems = appOrderItems.stream()
                .filter(e -> (e.getEnrollInfo() != null || OrderItemTypeEnum.SIGN_IN.getValue().equals(e.getItemType())))
                .collect(Collectors.toList());
        appOrderDetailVo.setEnrollOrderItems(enrollOrderItems);
        // 团购子单
        List<AppOrderItemVo> groupOrderItems = appOrderItems.stream()
                .filter(e -> (e.getEnrollInfo() == null || OrderItemTypeEnum.GOODS.getValue().equals(e.getItemType())))
                .collect(Collectors.toList());
        appOrderItems.clear();
        appOrderItems.addAll(groupOrderItems);
    }


    private void processEnrollInfo(List<AppOrderItemVo> appOrderItems, AppOrderDetailVo appOrderDetailVo) {
        List<AppOrderItemVo> enrollOrderItems = appOrderDetailVo.getEnrollOrderItems();
        if (CollectionUtils.isEmpty(enrollOrderItems)) {
            return;
        }
        for (AppOrderItemVo appOrderItemVo : enrollOrderItems) {
            String enrollInfo = appOrderItemVo.getEnrollInfo();
            if (!StringUtils.isEmpty(enrollInfo)) {
                // 报名信息
                List<OrderEnrollInfoVo> orderEnrollInfoVos = new ArrayList<>();

                List<ActiveEnrollInfoSonDto> activeEnrollInfoSonDtos = JSON.parseArray(enrollInfo, ActiveEnrollInfoSonDto.class);
                for (ActiveEnrollInfoSonDto activeEnrollInfoSonDto : activeEnrollInfoSonDtos) {
                    String title = activeEnrollInfoSonDto.getTitle();
                    Integer sort = activeEnrollInfoSonDto.getSort();

                    OrderEnrollInfoVo orderEnrollInfoVo = new OrderEnrollInfoVo();
                    orderEnrollInfoVo.setTitle(title);
                    orderEnrollInfoVo.setSort(sort);

                    // 类型(1-填写项，2-单选项，3-多选项)
                    Integer type = activeEnrollInfoSonDto.getType();
                    if (ActiveEnrollInfoTypeEnum.WRITE.getValue().equals(type)) {
                        // 填写
                        orderEnrollInfoVo.setValue(activeEnrollInfoSonDto.getContent());
                    } else if (ActiveEnrollInfoTypeEnum.SINGLE.getValue().equals(type)) {
                        // 单选
                        StringBuilder valueStringBuilder = new StringBuilder();
                        List<ActiveEnrollInfoOptionDto> activeEnrollInfoOptions = activeEnrollInfoSonDto.getActiveEnrollInfoOptions();
                        for (ActiveEnrollInfoOptionDto activeEnrollInfoOption : activeEnrollInfoOptions) {
                            // 勾选状态：1-未勾选，2-已勾选
                            Integer checkState = activeEnrollInfoOption.getCheckState();
                            if (checkState != null && checkState == 2) {
                                String optionText = activeEnrollInfoOption.getOptionText();
                                valueStringBuilder.append(optionText).append("、");
                            }
                        }

                        if (valueStringBuilder.length() > 0) {
                            valueStringBuilder.deleteCharAt(valueStringBuilder.length() - 1);
                            String value = valueStringBuilder.toString();
                            orderEnrollInfoVo.setValue(value);
                        }
                    } else {
                        // 多选
                        StringBuilder valueStringBuilder = new StringBuilder();
                        List<ActiveEnrollInfoOptionDto> activeEnrollInfoOptions = activeEnrollInfoSonDto.getActiveEnrollInfoOptions();
                        for (ActiveEnrollInfoOptionDto activeEnrollInfoOption : activeEnrollInfoOptions) {
                            // 勾选状态：1-未勾选，2-已勾选
                            Integer checkState = activeEnrollInfoOption.getCheckState();
                            if (checkState != null && checkState == 2) {
                                String optionText = activeEnrollInfoOption.getOptionText();
                                valueStringBuilder.append(optionText).append("、");
                            }
                        }

                        if (valueStringBuilder.length() > 0) {
                            valueStringBuilder.deleteCharAt(valueStringBuilder.length() - 1);
                            String value = valueStringBuilder.toString();
                            orderEnrollInfoVo.setValue(value);
                        }
                    }

                    orderEnrollInfoVos.add(orderEnrollInfoVo);
                }

                // 根据排序值正序
                orderEnrollInfoVos = orderEnrollInfoVos.stream().sorted(Comparator.comparing(OrderEnrollInfoVo::getSort)).collect(Collectors.toList());
                appOrderDetailVo.setOrderEnrollInfos(orderEnrollInfoVos);

                appOrderItemVo.setEnrollInfo("");
            }
        }

//        // 清空
//        for (AppOrderItemVo appOrderItem : appOrderItems) {
//            appOrderItem.setEnrollInfo("");
//        }
    }

    private void processInviteReturnMsg(Integer stepPriceState, Long activeId, LocalDateTime endTime, BigDecimal orderPrice, AppOrderDetailVo appOrderDetailVo) {
        String inviteReturnMsg = "";
        // 已报名人数，固定报名人数：已有x人报名；阶梯报名人数：已有x人报名，可返y元（没有达到返现标准，就不显示返现）（购买报名订单存在）
        if (StepPriceStateEnum.YES.getValue().equals(stepPriceState)) {
            // 阶梯报名人数：已有x人报名，可返y元（没有达到返现标准，就不显示返现）

            // 查找阶梯价格配置
            List<ActiveStepPriceVo> activeStepPriceVos = activeStepPriceApi.listByActiveIds(Collections.singletonList(activeId)).unpack();

            // 根据阶梯报名人数正序
            activeStepPriceVos = activeStepPriceVos.stream()
                    .sorted(Comparator.comparing(ActiveStepPriceVo::getEnrollNum))
                    .collect(Collectors.toList());

            // 当前报名活动已经报名成功的用户数
            int enrolledNum = 0;
            List<TbOrderItemPo> activeEnrollOrderItemPos = orderItemMapper.selectList(new QueryWrapper<TbOrderItemPo>().eq("del_state", 0)
                    .eq("active_id", activeId).isNotNull("enroll_info"));
            if (!CollectionUtils.isEmpty(activeEnrollOrderItemPos)) {
                // 过滤符合报名条件的用户（只要在活动结束前没取消的都算，活动结束后取消也算）
                for (TbOrderItemPo orderItemPo : activeEnrollOrderItemPos) {
                    // 如果用户取消参与活动，且活动结束时间不早于取消活动时间，则不计入报名用户数
                    if (SubOrderStateEnum.CANCEL.getValue().equals(orderItemPo.getSubOrderState())
                            && endTime.compareTo(orderItemPo.getCancelTime()) >= 0) {
                        continue;
                    }

                    enrolledNum += 1;
                }
            }

            ActiveStepPriceVo activeStepPriceVo = activeStepPriceVos.get(0);
            Integer firstEnrollNum = activeStepPriceVo.getEnrollNum();
            if (enrolledNum < firstEnrollNum) {
                // 报名成功，未满第一档人数，支付完成后提示：还差x人即可开启活动
                inviteReturnMsg = String.format("已有%s人报名", enrolledNum);
            } else {
                // 报名成功，满第一档人数，支付完成后提示：再邀x人，可返y元（对比第二档人数，逐级判断）

                // 可返x元
                BigDecimal returnAmt = BigDecimal.ZERO;
                for (ActiveStepPriceVo activeStepPrice : activeStepPriceVos) {
                    Integer enrollNum = activeStepPrice.getEnrollNum();
                    BigDecimal enrollPrice = activeStepPrice.getEnrollPrice();

                    // 取下一阶级的报名人数对比，如果都没匹配上，则表示已满员
                    if (enrolledNum <= enrollNum) {
                        // 计算可返金额=当前报名价格-对应阶级报名价格
                        returnAmt = orderPrice.subtract(enrollPrice);
                        break;
                    }
                }

                if (enrolledNum > 0) {
                    if (returnAmt.compareTo(BigDecimal.ZERO) > 0) {
                        inviteReturnMsg = String.format("已有%s人报名，全核销可返%s元", enrolledNum, returnAmt);
                    } else {
                        inviteReturnMsg = String.format("已有%s人报名", enrolledNum);
                    }
                }
            }
        } else {
            // 固定报名人数：已有x人报名

            // 如果是固定人数,关闭未满自动退,上面显示恭喜您报名成功 ,下面显示已有x人报名
            // 如果固定人数,开启未满自动退,上面显示还差x人即可开启活动  下面显示已有x人参团

            // 当前报名活动已经报名成功的用户数
            int enrolledNum = 0;
            List<TbOrderItemPo> activeEnrollOrderItemPos = orderItemMapper.selectList(new QueryWrapper<TbOrderItemPo>().eq("del_state", 0)
                    .eq("active_id", activeId));
            if (!CollectionUtils.isEmpty(activeEnrollOrderItemPos)) {
                // 过滤符合报名条件的用户（只要在活动结束前没取消的都算，活动结束后取消也算）
                for (TbOrderItemPo orderItemPo : activeEnrollOrderItemPos) {
                    // 如果用户取消参与活动，且活动结束时间不早于取消活动时间，则不计入报名用户数
                    if (SubOrderStateEnum.CANCEL.getValue().equals(orderItemPo.getSubOrderState())
                            && endTime.compareTo(orderItemPo.getCancelTime()) >= 0) {
                        continue;
                    }

                    enrolledNum += 1;
                }
            }

            if (enrolledNum > 0) {
                inviteReturnMsg = String.format("已有%s人报名", enrolledNum);
            }
        }
        appOrderDetailVo.setInviteReturnMsg(inviteReturnMsg);
    }
}
